#include "core/log_context.hpp"

//  初始化 thread_local 静态成员变量
thread_local std::string LogContextManager::s_traceId;
thread_local std::string LogContextManager::s_spanId;

void LogContextManager::set_context(const std::string& trace_id, const std::string& span_id) {
    s_traceId = trace_id;
    s_spanId = span_id;
}


void LogContextManager::clear_context() {
    s_traceId.clear();
    s_spanId.clear();
}


std::string LogContextManager::get_trace_id() {
    return s_traceId;
}


std::string LogContextManager::get_span_id() {
    return s_spanId;
}

// 内部类ContextScope 
LogContextManager::ContextScope::ContextScope(const std::string& trace_id, const std::string& span_id) {
    // 保存当前上下文
    m_prevTraceId = LogContextManager::get_trace_id();
    m_prevSpanId = LogContextManager::get_span_id();

    // 设置新的上下文
    LogContextManager::set_context(trace_id, span_id);
}


LogContextManager::ContextScope::~ContextScope() {
    // 恢复之前的上下文
    LogContextManager::set_context(m_prevTraceId, m_prevSpanId);
}
